package com.xingfei.blog.controller.ThirdLoginController;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;
import com.xingfei.blog.common.JsonResult;
import com.xingfei.blog.constants.ErrorConstants;
import com.xingfei.blog.dto.UserInfoDTO;
import com.xingfei.blog.redisCluster.RedisClusterUtil;
import com.xingfei.blog.service.WebUserService;
import com.xingfei.blog.utils.*;
import com.xingfei.blog.vo.UserVO;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 第三方登陆接口 qq
 * Created by yhang on 2017/3/13.
 */
@Controller
@RequestMapping("/login")
public class QQLogin {

    private static Logger logger = LoggerFactory.getLogger(QQLogin.class);

    @Autowired
    private WebUserService webUserService;

    private static String Profix_qq = "qq:";

    private static String Profix_User = "user:";

    private String REMOTE_URL="http://jianyiblog.com:8808/web-upload/uploadFile/uploadByUrl";

    @Autowired
    private RedisClusterUtil redisCluster;

    @Value("${spring.activemq.broker-url}")
    private String brokerurl;

    @Value("${spring.activemq.user}")
    private String username;

    @Value("${spring.activemq.password}")
    private String password;

    /**
     * 跳转授权界面，设置request session
     * @param request
     * @param response
     */
    @RequestMapping(value = "/redirectQqUrl",method = RequestMethod.GET)
    public void redirectQqUrl(HttpServletRequest request,HttpServletResponse response){
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
        } catch (QQConnectException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * qq_login
     */
    @RequestMapping(value = "/qq",method = RequestMethod.GET)
    public String getCode(HttpServletRequest request, HttpServletResponse response)throws IOException {
        //解决回调页面乱码问题
        response.setContentType("text/html; charset=utf-8");
        try {
            AccessToken accessTokenByRequest = (new Oauth()).getAccessTokenByRequest(request);
            AccessToken accessTokenObj = accessTokenByRequest;
            String accessToken = null;
            String openID = null;
            long tokenExpireIn = 0L;
            if (accessTokenObj.getAccessToken().equals("")) {
            //我们的网站被CSRF攻击了或者用户取消了授权
            //做一些数据统计工作
                System.out.print("没有获取到响应参数");
            } else {
                accessToken = accessTokenObj.getAccessToken();
                OpenID openIDObj =  new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                //判断用户是否绑定qq
                Long userId = webUserService.getUserInfoByOpenId(openID);
                if(userId!=null){
                    UserVO user = webUserService.getUserAndUserInfoById(userId);
                    //设置缓存
                    String ip = IPUtil.getLocalIp(request);
                    String token = MD5Util.getMD5(ip + System.currentTimeMillis());
                    //校验通过，保存进redis
                    String value = JSON.toJSONString(user);
                    //30分钟
                    //RedisUtil.set(Profix_User + token, value, Integer.valueOf(60 * 30), 1);
                    redisCluster.set(Profix_User + token, value, Integer.valueOf(60 * 30));
                    CookieUtil.setCookieDefault(response, "token", token);
                    //保存用户信息到当前线程中
                    UserThreadLocal.set(user);
                    //加载数据
                    this.webUserService.firstToLoad(request, user);
                    //已绑定，登陆
                    return "index";
                }else {
                    //跳转绑定界面
                    //获取用户所在ip
                    String ip = IPUtil.getLocalIp(request);
                    //将从qq获取的信息缓存redis
                    UserInfoDTO userinfo = new UserInfoDTO();
                    userinfo.setUserName(qzoneUserInfo.getUserInfo().getNickname());
                    //qq头像转换存储
                    CloseableHttpClient httpClient = HttpClients.createDefault();
                    HttpGet httpGet = new HttpGet(REMOTE_URL+"?remoteUrl="+qzoneUserInfo.getUserInfo().getAvatar().getAvatarURL100());
                    CloseableHttpResponse execute = httpClient.execute(httpGet);
                    HttpEntity entity = execute.getEntity();
                    String requestResult = EntityUtils.toString(entity);
                    if(StringUtils.isNotEmpty(requestResult)){
                        userinfo.setAvatarUrl(requestResult);
                    }else {
                        //存储异常还是保存原始url
                        userinfo.setAvatarUrl(qzoneUserInfo.getUserInfo().getAvatar().getAvatarURL100());
                    }
                    userinfo.setQqOppenId(openID);
                    userinfo.setRegisterIp(ip);
                    String value = JSON.toJSONString(userinfo);
                    String token = MD5Util.getMD5(openID);
                    //RedisUtil.set(Profix_qq + token, value, Integer.valueOf(60*30), null);
                    redisCluster.set(Profix_qq + token, value, Integer.valueOf(60*30));
                    CookieUtil.setCookieDefault(response,"token_qq",token);
                    return "login/jianyi-login-qq";
                    }
                }
            } catch (QQConnectException e1) {
            e1.printStackTrace();
        }
        return null;
    }
    @RequestMapping("/bindQQ")
    public String bindQQ(){
        return "/login/jianyi-login-qq-bind";
    }

    /**
     * qq注册接口
     * @param request
     * @return
     */
    @RequestMapping("/qqRegist")
    public @ResponseBody JsonResult qqRegist(HttpServletRequest request,HttpServletResponse response){
        JsonResult jsonResult = null;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            try {
                Cookie cookie2 = CookieUtil.getCookie(request, "token_qq");
                if(cookie2!=null){
                    String token = cookie2.getValue();
                    if(StringUtils.isNotEmpty(token)){
                        //UserInfoDTO userDTO = JSON.parseObject(RedisUtil.get(Profix_qq + cookie2.getValue(), null), UserInfoDTO.class);
                        UserInfoDTO userDTO = JSON.parseObject(redisCluster.get(Profix_qq + cookie2.getValue()), UserInfoDTO.class);
                        //注册生成用户详情表
                        boolean flag = webUserService.thirdRegistAndSaveUserInfo(userDTO,request,response);
                        if(flag){
                            jsonResult = new JsonResult(ErrorConstants.SERVER_SUCCESS, "success");

                        }else {
                            jsonResult = new JsonResult(ErrorConstants.SERVER_ERROR, "注册失败，请重试！");
                        }
                    }
                }

            }catch (Exception e){
                logger.error("qqRegist error:",e);
                jsonResult = new JsonResult(ErrorConstants.SERVER_ERROR, "注册失败，请重试！");
                return jsonResult;
            }
        }
        return jsonResult;
    }
}
